<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 15:22:10
 * @LastEditTime: 2023-09-02 12:21:26
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 兼容老接口数据
 */

namespace App\Http\Controllers\OldController;

use App\Http\Services\Comprehensive\EmployeeService;
use App\Http\Services\Pro\PotService;
use App\Http\Services\Pro\ProcessesService;
use App\Http\Services\Storage\AllocationService;
use App\Http\Services\Storage\ProYarnService;
use App\Http\Services\System\BarcodeService;
use App\Models\BarcodeCount;
use App\Models\ProProcessesPass;
use App\Repositories\MpcAllocationRepository;
use App\Repositories\MpcLocationRepository;
use App\Repositories\ProProcessesPassRepository;
use App\Repositories\ProProcessesWipRepository;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Laravel\Lumen\Routing\Controller as BaseController;

/**
 * 老系统兼容接口
 * @property ProYarnService $pro_yarn
 * @property PotService $pot
 * @property ProcessesService $process
 * @property EmployeeService $employee
 * @property BarcodeService $barcode
 * @author sunkaiyuan
 */
class MfgController extends BaseController
    {

    public function __construct(
        ProYarnService $pro_yarn,
        PotService $pot,
        ProcessesService $process,
        EmployeeService $employee,
        BarcodeService $barcode
    ) {
        $this->pro_yarn = $pro_yarn;
        $this->pot      = $pot;
        $this->process  = $process;
        $this->employee = $employee;
        $this->barcode  = $barcode;
        }

    public function took()
        {
        $this->pro_yarn->took();
        }
    public function follow()
        {
        // process_pass
        return $this->pot->repository->whereCode(request("code"))->first()->process_pass()->with(['swipor', 'process'])->get();
        }

    public function list()
        {
        $request = request();
        if (isEmpty($request->code ?? null))
            $request->offsetUnset("code");

        // DB::enableQueryLog();
        $data = $this->pot->repository->condition($request, false)->getGrid();
        // return (DB::getQueryLog());
        return $data;
        }
    public function addFollow()
        {
        $request = request();
        return array_map(function ($item) use ($request)
            {
            $wip = $this->process->pass->wip->whereId($item['wip_id'])->first();
            if ($wip) {
                return $this->process->passswip($item['wip_id'], $item['qty'], $item['ci_qty'], 1, $item->pro_dept_id, null, $request->swipor_id, date("Y-m-d H:i:s"), $wip['faultle_quantity']);
                }
            else {
                fail("过数失败！可能重复刷卡！");
                }
            }, $request->list);
        }
    public function info()
        {
        $code = request("code");
        if (isNotEmpty($code))
            $this->pot->repository->whereCode($code);

        // DB::enableQueryLog();
        $data          = $this->pot->repository->condition(request(), false)->with(["process_pass" => ["swipor", "process"], "wip" => ["material", "company"]])->getOne();
        $route         = $this->pot->getRoute($data['id']);
        $data['route'] = $route;

        return $data;
        }

    public function employee()
        {
        // position.pro_process.name
        $request   = request();
        $condition = [
            "position.pro_process.name" => request("role_name"),
            "shift.name"                => (request("class") == "1" ? "生产合班" : "生产合班")
        ];

        $request->merge(['filter' => [$condition]]);

        $DATA = $this->employee->repository->condition($request, false)->getList();
        return $DATA;
        }
    public function barcodeStructData()
        {
        $wipdata = request("wip_ids");
        return ProProcessesWipRepository::whereIn("id", array_column($wipdata, "id"))->get()->map(function ($v) use ($wipdata)
            {
            $qtyb = ceil($v['faultle_quantity'] / 25);

            foreach ($wipdata as $item) {
                if ($item['id'] == $v->id) {
                    $qtyb = $item['qtyb'];
                    break;
                    }
                }
            $array        = [];
            $BarCodeCount = $v->BarCodeCount;
            $v->company;
            $v->material;
            $v->color;
            $v->color_revision;
            for ($i = $BarCodeCount->count + 1; $i <= $BarCodeCount->count + $qtyb; $i++) {
                $barcode = "0" . strtoupper(base_convert($BarCodeCount->id . substr("00000" . $i, -5), 10, 36));

                $v['barcode']  = $barcode;
                $v['barcode2'] = env('APP_URL') . "/scan/barcode/solution?b=" . $barcode;
                $array[]       = $v->toArray();
                }
            $BarCodeCount->count += $qtyb;
            $BarCodeCount->save();
            return [
                'struct' => $this->barcodeStruct($v),
                'data'   => createReport($array),
            ];
            });
        }
    public function getBarcodeCount($code)
        {
        $code10 = base_convert($code, 36, 10);
        $id     = substr($code10, 0, strlen($code10) - 5);
        return BarcodeCount::whereId($id)->first();
        }
    private function getCode($code)
        {
        $position = strripos($code, "b=");
        $position = $position > 0 ? $position + 2 : 0;
        return substr($code, $position, strlen($code) - $position);
        }
    public function allocKc()
        {
        $code    = request("barcode");
        $code    = $this->getCode($code);
        $storage = $this->getBarcodeCount($code)?->storage()->with(['location', 'material', 'color'])->get();
        return $storage?->map(function ($v) use ($code)
            {
            $v['barcode'] = $code;
            return $v;
            });
        }
    public function alloc()
        {
        DB::beginTransaction();
        $data                          = request()->toArray();
        $ReqData['billdate']           = date("Y-m-d");
        $ReqData['quantity']           = $data['quantity'];
        $ReqData['auxiliary_quantity'] = $data['auxiliary_quantity'];
        $ReqData['details']            = [$data];
        $data                          = (new MpcAllocationRepository)->autosave($ReqData);
        AllocationService::audit([$data->id]);
        DB::commit();
        }
    public function getPlace()
        {
        return MpcLocationRepository::whereBarcode(request("code"))->getOne();
        }
    public function DmFactorykc()
        {
        $code = request("barcode");
        $code = $this->getCode($code);
        $wip  = $this->getBarcodeCount($code)->wip()
            ->with(["pro_dept", "outfactory", 'location', 'material', 'color', 'creator', 'process'])
            ->get();
        // 
        return $wip?->map(function ($v) use ($code)
            {
            $next_process = ProProcessesWipRepository::run("getNextProcessByWip", [$v]);
            $next_process->pro_dept;
            $v['barcode']      = $code;
            $v['next_process'] = $next_process;
            return $v;
            });
        }
    //改过数，非倒毛收货
    public function dmReceiver()
        {
        $request = request();
        DB::beginTransaction();
        ProcessesService::passswip($request->wipid, $request->faultle_quantity, 0, 1, $request->pro_dept_id, 0, null, null, $request->out_quantity, $request->location_id);
        DB::commit();
        return true;
        }
    public function passList()
        {
        $req = request();
        return ProProcessesPass::whereCreator_id(auth()->user()->employee_id)->with(["creator", "process", "pro_pot" => ['material', 'color']])
            ->forPage($req->pageNum, $req->pageSize)
            ->orderBy("id", "desc")
            ->get();
        }
    public function deletePass()
        {
        DB::beginTransaction();
        ProProcessesPassRepository::run("deletePass", [request("id")]);
        DB::commit();
        }
    private function barcodeStruct($request)
        {

        $barcode = $this->barcode->repository->orWhere(function ($query) use ($request)
            {
            $query->whereCompany_id($request->company_id ?? 0);
            $query->whereMaterial_id($request->material_id ?? 0);
            })
            ->orWhere(function ($query) use ($request)
                {
                $query->whereMaterial_id($request->material_id ?? 0);
                })
            ->orWhere(function ($query) use ($request)
                {
                $query->whereCompany_id($request->company_id ?? 0);
                })
            ->orWhere(function ($query)
                {
                $query->whereCompany_id(0);
                $query->whereMaterial_id(0);
                })
            ->orWhere(function ($query)
                {
                $query->whereIsDefault(1);
                })
            ->orderBy("company_id", "desc")
            ->orderBy("material_id", "desc")
            ->first();
        if ($barcode->filepath)
            return Storage::disk("barcode")->get($barcode->filepath);
        }
    }